package org.fnzn.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.fnzn.base.BaseController;
import org.fnzn.core.ReType;
import org.fnzn.core.Result;
import org.fnzn.core.TableResultResponse;
import org.fnzn.bean.FrontInfoScsp;
import org.fnzn.entity.FrontInfoScspVo;
import org.fnzn.entity.ScspOpinionVo;
import org.fnzn.entity.TaskVo;
import org.fnzn.service.ScspProcessService;
import org.fnzn.util.CommonUtil;
import org.fnzn.util.ResultGenerator;
import com.alibaba.fastjson.JSON;
@Controller
@RequestMapping(value = "/process/")
public class ScspProcessController extends BaseController{
	@Autowired
	private ScspProcessService scspProcessService;
	
	@Autowired
	private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;
    
    @Autowired
    private HistoryService historyService;

    @Autowired
    private ProcessEngineFactoryBean processEngine;

    @Autowired
    private ProcessEngineConfiguration processEngineConfiguration;
    
    /**
     * 跳转审查审批流程页面
     * @param model
     * @return
     */
    @GetMapping(value = "showScsp")
    public String showScsp() {
      return "/act/scsp/scspList";
    }
    /**
     * 贷款申请编辑信息
     * @return
     */
    @GetMapping(value = "editScsp")
    public String editScsp() {
      return "/act/scsp/editScsp";
    }
    /**---------我的任务---------*/
    @GetMapping(value = "showTask")
    public String showTask(Model model){
      return "/act/task/taskList";
    }
    /**
     * 查询审查审批列表
     * @param scsp 查询条件  
     * @param page 页码
     * @param limit 页面尺寸
     * @return
     */
	@GetMapping(value = "showScspList/{state}")
    @ResponseBody
    public ReType showScspList(FrontInfoScsp scsp, String page, String limit,@PathVariable String state) {
      String userId=CommonUtil.getUser().getUser_id();
      scsp.setCustGrpJl(userId);
      if(StringUtils.isBlank(scsp.getCustName())){
    	  scsp.setCustName(null);
      }
      if(StringUtils.isBlank(scsp.getIdNo())){
    	  scsp.setIdNo(null);
      }
      scsp.setProcessState(state);//审批状态 0：未提交 1：流程中 2：已结束   
      return scspProcessService.findList(scsp, page, limit);
      
    }
    /**
     * 提交审查审批授信流程
     * @param scsp
     * @return
     */
    @PostMapping(value = "addScspProcess",produces = "application/json;charset=UTF-8")
    @ResponseBody    
    public Result addScsp(@RequestBody FrontInfoScspVo voScsp){
    	return scspProcessService.addScsp(voScsp);
    }
    /**
     * 客户经理取消流程
     * @param scsp
     * @return
     */
    @DeleteMapping(value = "delete/{scspId}",produces = "application/json;charset=UTF-8")
    @ResponseBody    
    public Result deleteScsp(@PathVariable String scspId){
    	scspProcessService.deleteScsp(scspId);
    	return ResultGenerator.genSuccessResult("删除成功");
    }
    /**
     * 根据 执行对象id获取审批信息 返回页面
     * @param model
     * @param processId
     * @return
     */
	@GetMapping("scspOption")
    public String scspOption(Model model,String processId){
      List<ScspOpinionVo> optionList=scspProcessService.findOptionList(processId);
      model.addAttribute("scspOption",JSON.toJSONString(optionList));
      return "/act/scsp/scspOption";
    }
    /**
     * 根据 执行对象id获取审批信息 返回json
     * @param processId
     * @return
     */
	@GetMapping("optionList")
	@ResponseBody 
    public Result optionList(String processId){
	  List<ScspOpinionVo> optionList=scspProcessService.findOptionList(processId);
      return ResultGenerator.genSuccessResult(new TableResultResponse<ScspOpinionVo>(optionList.size(),optionList));
    }
    /**
     * 查询任务列表
     * @param task
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "showTaskList")
    @ResponseBody
    public ReType showTaskList(TaskVo task, String page, String limit) {    
      return scspProcessService.showTaskList(task, page, limit);
    }
    /**
     * 跳转审批办理页面
     * @param model
     * @param taskId
     * @return
     */
    @GetMapping("agent/{id}/{taskName}")
    public String agent(Model model,@PathVariable("id") String taskId,@PathVariable("taskName") String taskName){
      model.addAttribute("taskId",taskId);
      model.addAttribute("taskName",taskName);
      return "/act/task/task-agent";
    }
    /**
     * 审批结果提交
     * @param op
     * @return
     */
	@PostMapping("agent/complete")
    @ResponseBody
    public Result complete(@RequestBody ScspOpinionVo op){
	  String name = scspProcessService.complete(op);
      return ResultGenerator.genSuccessResult("审核成功"+(op.getFlag().equals("T")?"[通过]":(op.getFlag().equals("F")?"[拒绝]":"[驳回]"))+","+(name==null?"流程结束":"提交至"+name));
    }
    
    /**
     * 追踪图片成图
     * @param request
     * @param resp
     * @param processInstanceId
     * @throws IOException
     */
    @GetMapping("getProcImage")
    public void getProcImage(HttpServletResponse resp,String processInstanceId)
        throws IOException {
      ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      HistoricProcessInstance historicProcessInstance =
              historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      String processDefinitionId=null;
      List<String> executedActivityIdList = new ArrayList<String>();
      if(processInstance!=null){
        processDefinitionId=processInstance.getProcessDefinitionId();
        executedActivityIdList=this.runtimeService.getActiveActivityIds(processInstance.getId());
      }else if(historicProcessInstance!=null){
        processDefinitionId=historicProcessInstance.getProcessDefinitionId();
        List<HistoricActivityInstance> historicActivityInstanceList =
                historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceId().asc().list();
        for (HistoricActivityInstance activityInstance : historicActivityInstanceList) {
          executedActivityIdList.add(activityInstance.getActivityId());
        }
      }

      if(StringUtils.isEmpty(processDefinitionId)||executedActivityIdList.isEmpty()){
        return;
      }
      BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
      //List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
      processEngineConfiguration = processEngine.getProcessEngineConfiguration();
      Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);
      ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
      //List<String> activeIds = this.runtimeService.getActiveActivityIds(processInstance.getId());

      InputStream imageStream=diagramGenerator.generateDiagram(
          bpmnModel, "png",
              executedActivityIdList, Collections.<String>emptyList(),
          processEngine.getProcessEngineConfiguration().getActivityFontName(),
          processEngine.getProcessEngineConfiguration().getLabelFontName(),
          "宋体",
          null, 1.0);
      byte[] b = new byte[1024];
      int len;
      while ((len = imageStream.read(b, 0, 1024)) != -1) {
        resp.getOutputStream().write(b,0,len);
      }
    }

}
